from itsdangerous.jws import TimedJSONWebSignatureSerializer as TJWSSerialize
from django.conf import settings

from users.models import User


def encode_openid(openid):
    serizlier = TJWSSerialize(settings.SECRET_KEY, expires_in=300)

    token = serizlier.dumps({'openid': openid})
    return token.decode()


def decode_openid(token):
    serizlier = TJWSSerialize(settings.SECRET_KEY, expires_in=300)
    try:
        openid = serizlier.loads(token).get('openid')
    except Exception as e:
        return None
    return openid


def generate_verify_url(user, email):
    user_data = {
        "id": user.id,
        "email": email,
    }

    serizlier = TJWSSerialize(secret_key=settings.SECRET_KEY, expires_in=300)
    token = serizlier.dumps(user_data).decode()
    url = 'http://www.meiduo.site:8000/verify/emails?token=%s' % token

    return url


def decode_verify_url(token):
    serizlier = TJWSSerialize(settings.SECRET_KEY, expires_in=3000)
    try:
        user_dict = serizlier.loads(token)
        user_id = user_dict.get("id")
        user = User.objects.get(id=user_id)
    except Exception:
        return None
    else:
        return user
